<template>
  <div class="add-essay-wrap">
    <div class="aew-btns">
      <el-button type="primary" plain>预览</el-button>
      <el-button @click="saveEssay" type="primary" plain>保存</el-button>
    </div>
    <el-form ref="essayFormRef" :model="form" :rules="rules" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="文章标题" prop="artTitle">
            <el-input v-model="form.artTitle" placeholder="请输入文章标题"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="文章分类" prop="artCategory">
            <tree-select
              v-model="form.artCategory"
              :options="categoryData"
              :normalizer="normalizer"
              :show-count="true"
              @select="handleCategoryChange"
              placeholder="选择上级菜单"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="文章来源" prop="artSource">
            <el-select v-model="form.artSource" placeholder="请选择文章来源">
              <el-option
                v-for="dict in dict.type.art_source"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="文章类型" prop="artType">
            <el-select v-model="form.artType" placeholder="请选择文章类型">
              <el-option
                v-for="dict in dict.type.art_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="文章作者" prop="artAuthor">
            <el-input v-model="form.artAuthor" placeholder="请输入文章实际作者"/>
          </el-form-item>
        </el-col>
        <el-col :span="8"></el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="文章摘要" prop="artAbstract">
            <el-input type="textarea" v-model="form.artAbstract" placeholder="请输入文章摘要"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="文章内容">
            <editor v-model="form.artContent" :min-height="600"/>
          </el-form-item>
        </el-col>
      </el-row>
      <!--<el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="会员专享">
            <editor v-model="form.artMemberContent" :min-height="400"/>
          </el-form-item>
        </el-col>
      </el-row>-->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="是否展示" prop="artShowFlag">
            <el-switch v-model="form.artShowFlag" :active-value="1" :inactive-value="0"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="看广告展示" prop="artShowAdv">
            <el-switch v-model="form.artShowAdv" :active-value="1" :inactive-value="0"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="文章发布时间" prop="artPublishTime">
            <el-date-picker clearable
                            v-model="form.artPublishTime"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择文章发布时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="文章置顶" prop="artTop">
            <el-switch v-model="form.artTop" :active-value="1" :inactive-value="0"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="文章权重" prop="artWeight">
            <el-input v-model="form.artWeight" placeholder="请输入文章权重"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="关联圈子" prop="circleId">
            <el-input v-model="form.circleId" placeholder="请输入关联到圈子"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="16">
          <el-form-item label="文章标签" prop="artTag">
            <el-input @focus="handleOpenSelectTag" v-model="form.artTag" placeholder="请输选择文章标签"/>
            <!--<el-select
              v-model="form.artTag"
              multiple
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="remoteTagMethod"
              :loading="tagLoading">
              <el-option
                v-for="item in artTagList"
                :key="item.id"
                :label="item.tagName"
                :value="item.id">
              </el-option>
            </el-select>-->
          </el-form-item>
        </el-col>
      </el-row>
      <template v-if="form.artType == '2'">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="行业" prop="jobTrade">
              <el-select v-model="form.essayJob.jobTrade" placeholder="请选择行业">
                <el-option
                  v-for="dict in dict.type.job_trade"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工作地点" prop="jobProvince">
              <region-group v-model="form.region" @change="addressChange"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="详细地址" prop="jobAddress">
              <el-input v-model="form.essayJob.jobAddress" placeholder="请输入详细地址"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="线上报名" prop="jobAttend">
              <el-switch v-model="form.essayJob.jobAttend" :active-value="1" :inactive-value="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item v-if="form.essayJob.jobAttend == 1" label="开始时间" prop="jobStart">
              <el-date-picker
                v-model="form.essayJob.jobStart"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item v-if="form.essayJob.jobAttend == 1" label="结束时间" prop="jobEnd">
              <el-date-picker
                v-model="form.essayJob.jobEnd"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="工作时间" prop="jobWorkTime">
              <el-input v-model="form.essayJob.jobWorkTime" placeholder="请输入工作时间"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="薪资" prop="jobPrice">
              <el-input v-model="form.essayJob.jobPrice" placeholder="请输入薪资"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="薪资单位" prop="jobPriceUnit">
              <el-input v-model="form.essayJob.jobPriceUnit" placeholder="请输入薪资单位"/>
            </el-form-item>
          </el-col>
        </el-row>
      </template>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="文章图片">
            <image-upload v-model="form.fileList" :limit="20"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="文章大图">
            <image-upload v-model="form.artBigImage"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="文章中图">
            <image-upload v-model="form.artMedImage"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="文章小图">
            <image-upload v-model="form.artMinImage"/>
          </el-form-item>
        </el-col>
      </el-row>
      <!--<el-form-item label="文章发布时间" prop="artPublishTime">
        <el-date-picker clearable
                        v-model="form.artPublishTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择文章发布时间">
        </el-date-picker>
      </el-form-item>-->
    </el-form>
  </div>
</template>

<script>
import { RegionGroup } from 'v-region'
import TreeSelect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getArtEssay, addArtEssay, updateArtEssay} from "@/api/art/artEssay";
import {listArtCategoryAll} from "@/api/art/artCategory";
import {getJobByArtId} from "@/api/art/artEssayJob";
import {listArtTag} from "@/api/art/artTag";

export default {
  name: 'AddEssay',
  dicts: ['art_source', 'art_type', 'job_trade'],
  components: {RegionGroup, TreeSelect},
  data() {
    return {
      form: {
        region: {
          province: '',
          city: '',
          area: '',
          town: ''
        },
        essayJob: {},
      },
      rules: {
        artTitle: [
          { required: true, message: "文章标题不能为空", trigger: "blur" }
        ],
        artCategory: [
          { required: true, message: "文章分类不能为空", trigger: "blur" }
        ],
        artSource: [
          { required: true, message: "文章来源不能为空", trigger: "blur" }
        ],
        artType: [
          { required: true, message: "文章类型不能为空", trigger: "blur" }
        ],
      },
      categoryData: [],
      artTagList: [],
      tagLoading: false,
    }
  },
  created() {
    this.loadEssay();
    this.getTreeSelect();
  },
  methods: {
    loadEssay() {
      if (this.$route.query.id) {
        getArtEssay(this.$route.query.id).then(response => {
          this.form = response.data;
          if (!this.form.essayJob) {
            this.form.essayJob = {};
          }
          if (this.form.artType === '2') {
            this.loadJobInfo(this.form.id);
          }
        });
      }
    },
    loadJobInfo(id) {
      getJobByArtId(id).then(res => {
        if (res.code === 200) {
          this.form.essayJob = res.data;
          const region = {}
          region.province = this.form.essayJob.jobProvince;
          region.city = this.form.essayJob.jobCity;
          region.area = this.form.essayJob.jobArea;
          region.town = '';
          this.form.region = region;
        }
      });
    },
    handleFormData() {
      // 处理表单数据
      // this.form.region = null;
    },
    handleFileData() {
      if (this.form.fileList && typeof this.form.fileList === 'string') {
        const arr = this.form.fileList.split(',');
        const fileArr = [];
        arr.forEach(item => {
          fileArr.push({
            fileName: item,
            filePath: item,
          })
        });
        this.form.fileList = fileArr;
      }
    },
    saveEssay() {
      this.handleFileData();
      this.$refs["essayFormRef"].validate(valid => {
        if (valid) {
          this.handleFormData();
          if (this.form.id != null) {
            updateArtEssay(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.goBack();
            });
          } else {
            addArtEssay(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.goBack();
            });
          }
        }
      });
    },
    /** 地址变化触发 */
    addressChange(data) {
      if (data.province) {
        this.form.essayJob.jobProvinceName = data.province.value;
      }
      if (data.city) {
        this.form.essayJob.jobCityName = data.city.value;
      }
      if (data.area) {
        this.form.essayJob.jobAreaName = data.area.value;
      }
      this.form.essayJob.jobProvince = this.form.region.province;
      this.form.essayJob.jobCity = this.form.region.city;
      this.form.essayJob.jobArea = this.form.region.area;
    },
    /** 文章分类变化触发 */
    handleCategoryChange(node) {
      this.form.artCategoryName = node.categoryName;
    },
    /** 查询文章分类管理下拉树结构 */
    getTreeSelect() {
      listArtCategoryAll({}).then(res => {
        if (res.code === 200) {
          this.categoryData = [];
          const data = { id: 0, categoryName: '文章分类', level: 0, children: [] };
          data.children = this.handleTree(res.data, "id", "pid");
          this.categoryData = [...data.children];
        }
      });
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.categoryName,
        children: node.children
      };
    },
    // 返回列表页
    goBack() {
      this.closeSelectedTag({
        path: this.$route.path
      });
    },
    /** 关闭选中标签卡 */
    closeSelectedTag(view) {
      this.$tab.closePage(view).then(({ visitedViews }) => {
        this.$router.push({
          path: '/art/artEssay',
          query: {
            dateTime: new Date().getTime()
          }
        });
      });
    },
    /** 打开文章标签选择 */
    handleOpenSelectTag() {
      // todo
    },
    /** 远程搜索 */
    remoteTagMethod(query) {
      if (query !== '') {
        this.loading = true;
        listArtTag({tagName: query}).then(res => {
          if (res.code === 200) {
            this.artTagList = res.data;
          }
          this.loading = false;
        }).catch(err => {
          this.loading = false;
        });
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.add-essay-wrap {
  padding: 20px;

  .aew-btns {
    margin-bottom: 20px;
    text-align: right;
  }

  .el-select {
    width: 100%;
  }

}
</style>
